<!--
*@Author: QWP
*@Description: 用户，群名列表
*@Params: types 1 群聊   2 个人    3 系统通知
*@Date: 2024-07-11 13:35:40
-->
<template>
  <u-collapsed-sider width="320px">
    <a-layout class="f-h-100 u-chat-user-list"
      ref="userListRef"
      id="userListBox">
      <a-layout-header class="f-h-auto" 
        style="padding: 20px 14px 14px; background-color: #fff; line-height: 36px;">
        <!-- 人员搜索 -->
        <a-popover placement="right" trigger="contextmenu"
          v-model:open="showSearchResult">
          <template #content>
            <a-list :data-source="loadUses"
              :loading="loading"
              style="max-height: 300px; overflow: auto">
              <template #renderItem="{ item, index }">
                <a-list-item @click="selectUser(item)">
                  <div  style="width: 240px">
                    <a-row>{{ item.groupNames }}</a-row>
                    <a-row>{{ item.fkdeptname }}</a-row>
                  </div>
                </a-list-item>
              </template>
            </a-list>
          </template>
          <div class="u-search-box">
            <a-input v-model:value="searchValue"
              allowClear
              @focus="isFocus = false" 
              @blur="isFocus = true;"
              @change="filterList">
            </a-input>

            <div class="u-search-input-label" v-if="isFocus && !searchValue" >
              <a-space size="small">
                <SearchOutlined />
                <span>搜索</span>
              </a-space>
            </div>
          </div>
        </a-popover>

      </a-layout-header>

      <a-layout-content class="s-bg-white"
        style="overflow: auto;">
        <a-list :data-source="userList"
          :loading="loading">
          <template #renderItem="{ item, index }">
            <UserRightMenu v-model:open="showRight['visible' + index]"
              :data="item"
              @click="(value, menu) => rightMenuClick(value, menu, item, index)">
              <a-list-item
                :class="{'u-chat-current': curentGroup == item.keyid}"
                class="f-position-relative"
                @click="currentClick(item, index)"
                @contextmenu="(event) => contextmenu(item, index, event)">

                <template v-if="item.status == 1">
                  <u-icon-font type="icon-a-zhiding3" class="u-top-icon"></u-icon-font>
                </template>

                <a-row align="middle" 
                  justify="space-between" 
                  class="f-user-item f-w-100" >
                  <a-col :span="4">
                    <a-avatar :size="40" 
                      :style="{ 
                        backgroundColor: item.types == 3 ? '#f56a00' : '#00a2ae', 
                        verticalAlign: 'middle' 
                      }"
                      shape="square">
                      {{ (item['groupNames'] || '')[0] }}
                    </a-avatar>
                  </a-col>
                  <a-col :span="16">
                    <div class="u-group-name" >{{ item.groupNames }}</div>
                    <div class="u-chat-msg" v-if="item.content ">{{ item.content }}</div>
                    <div class="u-chat-msg" v-else-if="item.fileName">{{ item['fileName'] }}</div>
                  </a-col>
                  <a-col :span="4" align="center">
                    <div class="u-chat-date" >{{ getDate(item.time) }}</div>
                    <a-row justify="center" v-if="item.numbers && item.numbers > 0">
                      <!-- <a-tag color="#f50">{{ item.number }}</a-tag> -->
                      <a-badge :count="item.numbers" />
                    </a-row>
                  </a-col>
                </a-row>
              </a-list-item>
            </UserRightMenu>
          </template>
        </a-list>
      </a-layout-content>
    </a-layout>
  </u-collapsed-sider>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, watch } from 'vue' 
import { useRoute, useRouter } from 'vue-router'
import { urlFile, numberC } from '@/util/common'
import { throttle, debounce } from '@/util/format.ts'
import { cloneDeep } from 'lodash'
import * as chatApi from '@/service/emergency/chat'
import * as groupApi from '@/service/emergency/group'
import { chatEventBus } from '@/util/eventBus'
import dayjs from 'dayjs'
import * as linkApi from '@/service/personal/link_book'
import { Item } from 'ant-design-vue/es/menu'
import UserRightMenu from './UserRightMenu.vue'

interface Props {
  current?: any,
  isDialog?: boolean,
  isOpen?: boolean, // 是否是打开
  dialogOpen?: boolean, // 是否打开侧边栏
  currentUser?: object | null, // 选择人员打开聊天窗
  keyUnNumber?: object, // 未读消息
}
const props = defineProps<Props>()

const searchValue = ref<string>('');
const isFocus = ref<boolean>(true);

// 选中的聊天
const curentGroup = ref<string>('')

const emits = defineEmits(['click'])

const loading = ref<boolean>(false)
const originList: Array<any> = ref([])
const userList: Array<any> = ref([])
const getList = async (isZd?: boolean)  => {
  loading.value = true;
  try {
    const res = await chatApi.getMessage({
      current: 1,
      model: {},
      size: 5000,
    });
    if(res.code == 0) {
      const groupList = res.data.chatList.groupList.records || []
      
      groupList.forEach(item => {
        let tKeyUnNumber = props['keyUnNumber'] || {};
        let unNumber = props.keyUnNumber[item.keyid] || 0;
        // item.number = numberC(unNumber) + numberC(item.number)
        item.time = item['chattime'] || ''
        item.content = item['lastMessage'] || ''
      })

      if(props.currentUser) {
        let index = groupList.findIndex(i => i.keyid == props.currentUser['keyid'])
        if(index == -1) {
          groupList.unshift(props.currentUser)
        }
      }

      userList.value = groupList;
      originList.value = groupList;

      // 不是置顶重载列表
      if(isZd != true) {
        let tCurrent = props.currentUser ? props.currentUser : userList.value[0]
        let index = userList.value.findIndex(o => o.keyid == tCurrent['keyid'])
        index = index == -1 ? 0 : index
  
        curentGroup.value = tCurrent['keyid']
        userList.value[index]['numbers'] = 0
        originList.value[index]['numbers'] = 0
        emits('click', tCurrent)

        // 清除首页悬浮按钮的未读数量
        chatEventBus.emit('setFloatUnNum', { keyid: curentGroup.value, value: 0 })
      }

    }
  } catch (error) {}
  loading.value = false;
}

// 搜索加载
const showSearchResult = ref<boolean>(false)
const loadUses = ref<any[]>([])

// 加载远程的人员
const searchUer = ref<any[]>([])
const getLoadSUer = async () => {
  try {
    let form = {
      model: {
        // keywords: searchValue.value.trim()
      },
      size: 2000000,
      current: 1
    }
    const res = await linkApi.page(form)
    if(res.code == 0) {
      searchUer.value = res.data.records || [];
      searchUer.value.forEach(item => {
        item.groupNames = item.fkusername;
        item.keyid = item.fkuserid;
        item.types = 2
      })
    }
  } catch (error) {}
}

// 获取加入的群聊数据
const groupList = ref<any[]>([])
const getGroupList = async () => {
  try {
    const res = await groupApi.page({
      current: 1,
      model: { type: 1 },
      size: 5000
    })
    if(res.code == 0) {
      groupList.value = res.data['records'] || [];
      groupList.value.forEach(item => {
        item.types = 1;
        item.fkdeptname = '群聊'
      })
    }
  } catch (error) {}
}

// 群,用户筛选
const userListIds = computed(() => userList.value.map(i => i.keyid))
const filterList = async (e) => {
  const tVal = searchValue.value.trim();
  loadUses.value = tVal ? [...searchUer.value, ...groupList.value].filter(item => item.groupNames.includes(tVal)) : [];
  if(loadUses.value.length > 0) {
    showSearchResult.value = true
  }
}

// 筛选出的人，选择事件
const selectUser = (item) =>  {
  loadUses.value = [];
  showSearchResult.value = false;
  searchValue.value = '';
  userList.value = cloneDeep(originList.value)
  if(!userListIds.value.includes(item['keyid'])) {
    originList.value.unshift(item)
    userList.value.unshift(item)
  }
  curentGroup.value = item.keyid;
  
  emits('click', item)
  chatEventBus.emit('setFloatUnNum', { keyid: curentGroup.value, value: 0 })
}

// 点击事件
const currentClick = (data, index) => {
  curentGroup.value = data.keyid;
  userList.value[index] = { ...data, numbers: 0 }
  originList.value[index] = { ...data, numbers: 0 }

  // 清除首页悬浮按钮的未读数量
  chatEventBus.emit('setFloatUnNum', { keyid: curentGroup.value, value: 0 })

  emits('click', data)
}

// 右键菜单点击事件
const rightMenuClick = (value, menu, rowData, index) => {
  switch(value) {
    case 'top':
      topUser(rowData, index);
      break
  }  
}

// 置顶
const topUser = async (data, index) => {
  try {
    const form = {
      id: data.id,
      status: data.status == 0 ? '1' : '0'
    }
    const res = await chatApi.setStatus(form);
    if(res.code == 0) {
      getList(true)
    }
    else {
      messageC(res.msg)
    }
  } catch (error) {}
}

// 获取实时信息
const getBus = () => {
  chatEventBus.on('realMsg', (message) => {
    const { groupId, sender, chatType } = message;
    if(!chatType) {
      return
    }

    const matchId = { 1: 'groupId', 2: 'sender' }
    if(message[matchId[chatType]] == curentGroup.value) {
      return
    }

    let index = userList.value.findIndex(i => i.keyid == message[matchId[chatType]]);
    if(index != -1) {
      let item = userList.value[index];
      item['numbers'] = numberC(item['numbers']) + 1;
      userList.value[index] = { ...item, ...message, content: message['message'] || ''  }
      originList.value[index] = { ...item, ...message, content: message['message'] || '' }
    }
  })

  chatEventBus.on('updateGoupMsg', updateGoupMsg)
}

// 获取时间
const getDate = (time) => {
  return time ? dayjs(time).format("HH:mm") : ''
}

const showRight = ref<object>({})
const rightCurrentRow = ref<object>({})
const rightIndex = ref<number>(-1)
const contextmenu = (item, index, event) => {
  showRight.value = {}
  event.preventDefault();
  rightIndex.value = index;
  rightCurrentRow.value = item;
  showRight.value['visible' + index] = true
}

// 设置页面的右键事件
const rightEvent = () => {
  try {
    const el: HTMLElement = document.getElementById('userListBox')
  } catch (error) {}
  // userListRef.value.add
}

// 更新群聊最新的提示消息
const updateGoupMsg = ({ keyid, msg }) => {
  if(keyid) {
    let index = userList.value.findIndex(i => i.keyid == keyid);
    if(index == -1) {
      return
    }
    let currentData = userList.value[index]
    if(keyid != curentGroup.value) {
      currentData.numbers = numberC(currentData.numbers) + 1
    }
    const TMsg = {
      ...userList.value[index],
      time: msg['time'],
      content: msg['messageInfo'] || '',
      fileName: msg['fileName'],
    }
    userList.value.splice(index, 1, TMsg)
    originList.value.splice(index, 1, TMsg)
  }
}

onMounted(() => {
  getList();
  getLoadSUer();
  getGroupList();
  getBus()  
})

watch(() => props.isOpen, (nval, oval) => {
  if(Object.values(props.currentUser || {}).length != 0 && userList.value.length != 0) {
    getList()
    selectUser(props.currentUser)
    currentClick(props.currentUser)
  }
})

watch(() => props.dialogOpen, (nval, oval) => {
  if(nval == true) {
    getList()
  }
})

</script>

<style lang='scss'>
.u-chat-user-list {
  .u-search-box {
    position: relative;
    width: 100%;
    height: 32px;
    #u-user-search-input {
      background-color: #F2F2F2;
      &:focus {
        background-color: #fff;
      }
    }
    .u-search-input-label{
      position: absolute;
      z-index: 1;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      color: #999999;
    }
  }
  .ant-list-item {
    padding: 12px 12px;
    cursor: pointer;
    .f-user-item {
      .u-group-name {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 16px;
        color: #000000;
        line-height: 20px;
        text-overflow: ellipsis; 
        white-space: normal; 
        overflow: hidden
      }
      .u-chat-msg {
        padding: 4px 20px 0 0 ;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #B0B0B0;
        line-height: 17px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis
      }
      .u-chat-date {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #B0B0B0;
      }
    }
  }
  .u-chat-current {
    background: linear-gradient( 270deg, #1890FF 0%, #5CB0FD 100%);
    border-radius: 0px 0px 0px 0px;
    .u-group-name, .u-chat-msg, .u-chat-date {
      color: #fff !important;
    }
    .u-top-icon {
      color: #fff !important;
    }
  }
  .u-top-icon {
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    color: rgba($color: #1890ff, $alpha: 0.8);
  }
}
</style>